# views.py
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework import status

from .models import BayAssignedSegment
from .serializers import BayAssignedSegmentSerializer


class AddBayAssignedSegmentView(APIView):
    def post(self, request, *args, **kwargs):
        serializer = BayAssignedSegmentSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse({"data": serializer.data, "code": 200})
        else:
            return JsonResponse({"message": serializer.errors, "code": 400})


class BayAssignedSegmentListView(APIView):
    def get(self, request, format=None):
        # 获取查询参数
        bay_description = request.query_params.get('bay_description', '')
        ship_number = request.query_params.get('ship_number', '')
        page = request.query_params.get('current', 1)
        page_size = request.query_params.get('pageSize', 8)

        queryset = BayAssignedSegment.objects.all()

        if ship_number:
            queryset = queryset.filter(ship_number__icontains=ship_number)
        if bay_description:
            queryset = queryset.filter(bay_description__icontains=bay_description)

        # 分页处理
        paginator = Paginator(queryset, page_size)
        try:
            segments = paginator.page(page)
        except PageNotAnInteger:
            segments = paginator.page(1)
        except EmptyPage:
            segments = paginator.page(paginator.num_pages)

        serializer = BayAssignedSegmentSerializer(segments, many=True)

        return JsonResponse({
            "code": 200,
            "data": {
                "list": serializer.data,
                "total": paginator.count,
                "current": segments.number,
                "pageSize": page_size
            }
        }, status=status.HTTP_200_OK)


class BayAssignedSegmentDetailView(APIView):
    def get_object(self, pk):
        try:
            return BayAssignedSegment.objects.get(assignment_id=pk)
        except BayAssignedSegment.DoesNotExist:
            return None

    def get(self, request, pk, format=None):
        segment = self.get_object(pk)
        if not segment:
            return JsonResponse({"code": 404, "message": "未找到对应记录"}, status=status.HTTP_404_NOT_FOUND)
        serializer = BayAssignedSegmentSerializer(segment)
        return JsonResponse({"code": 200, "data": serializer.data}, status=status.HTTP_200_OK)

    def put(self, request, pk, format=None):
        segment = self.get_object(pk)
        if not segment:
            return JsonResponse({"code": 404, "message": "未找到对应记录"}, status=status.HTTP_404_NOT_FOUND)

        serializer = BayAssignedSegmentSerializer(segment, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse({"code": 200, "message": "修改成功", "data": serializer.data}, status=status.HTTP_200_OK)
        return JsonResponse({"code": 400, "message": "数据校验失败", "errors": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        segment = self.get_object(pk)
        if not segment:
            return JsonResponse({"code": 404, "message": "未找到对应记录"}, status=status.HTTP_404_NOT_FOUND)

        segment.delete()
        return JsonResponse({"code": 200, "message": "删除成功"}, status=status.HTTP_200_OK)


class BatchDeleteBayAssignedSegmentsView(APIView):
    def post(self, request, *args, **kwargs):
        entities = request.data.get('entities', [])

        if not isinstance(entities, list) or len(entities) == 0:
            return JsonResponse(
                {"code": 400, "message": "请传入有效的实体列表"},
                status=status.HTTP_400_BAD_REQUEST
            )

        ids_to_delete = [entity.get('assignment_id') for entity in entities if 'assignment_id' in entity]

        if not ids_to_delete:
            return JsonResponse(
                {"code": 400, "message": "实体列表中没有有效的 assignment_id"},
                status=status.HTTP_400_BAD_REQUEST
            )

        deleted_count, _ = BayAssignedSegment.objects.filter(assignment_id__in=ids_to_delete).delete()

        return JsonResponse(
            {"code": 200, "message": f"成功删除 {deleted_count} 条记录"},
            status=status.HTTP_200_OK
        )


class BatchAddBayAssignedSegmentsView(APIView):
    def post(self, request, *args, **kwargs):
        data_list = request.data.get('list', [])

        if not isinstance(data_list, list):
            return JsonResponse(
                {"code": 400, "message": "请求数据格式错误，'list' 应为数组"},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 序列化并验证所有数据
        serializer = BayAssignedSegmentSerializer(data=data_list, many=True)

        if serializer.is_valid():
            # 批量保存
            BayAssignedSegment.objects.bulk_create([
                BayAssignedSegment(**item) for item in serializer.validated_data
            ])
            return JsonResponse({
                "code": 200,
                "message": f"成功新增 {len(serializer.validated_data)} 条数据",
                "data": serializer.validated_data
            }, status=status.HTTP_200_OK)
        else:
            return JsonResponse({
                "code": 400,
                "message": "数据校验失败",
                "errors": serializer.errors
            }, status=status.HTTP_400_BAD_REQUEST)